<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共{{ total }}条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="uploadExcelFn">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="addEmployees">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格区域 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="120">
            <template slot-scope="scope">
              <imageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" sortable :sort-method="sortFn" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatFormFn" />
          <!-- <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              <span>{{ formatFormOfEmployees(row.formOfEmployment) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <template #default="{ row }">
              <!-- 格式化时间 -->
              {{ $dateFormat(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="addRoleBtnFn(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployees(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination :current-page="query.page" :page-sizes="[10, 15, 20, 25]" :page-size="query.size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-row>

        <!-- 添加员工弹窗 -->
        <el-dialog title="添加员工" :visible.sync="showEmpDialog" width="50%" @close="closeDialogFn">
          <empDialog ref="empForm" :depart-list="departList" @close="showEmpDialog=false" @submitEv="addEmp" />
        </el-dialog>
      </el-card>

      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible="showRoleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog :role-ids="roleIds" :role-list="roleList" @close="closeFn" @confirmEv="addRoleConfirmFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeeAPI, addEmployeeAPI, getRolesAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api'
import empDialog from './components/empDialog.vue'
import assignRoleDialog from './components/assignRoleDialog.vue'
import Employees from '@/api/constant/employees'
import { departmentsListAPI } from '@/api'
import { transTree } from '@/utils'
import imageHolder from '@/components/ImageHolder'

export default {
  name: 'Employees',
  components: {
    empDialog,
    imageHolder,
    assignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showEmpDialog: false, // 新增员工弹窗
      departList: [],
      showRoleDialog: false, // 分配权限弹窗
      roleList: [], // 角色列表
      userId: '', // 角色id
      roleIds: [] // 现有的角色列表
    }
  },
  created() {
    this.getEmployeesListFn()
    this.getRolesListFn()
  },
  methods: {
    // 获取员工列表
    async getEmployeesListFn() {
      const res = await getEmployeeListAPI(this.query)
      // 如果得到的结果数组长度为0,并且不是第一页的时候,回到前一页重新发请求
      if (res.data.rows.length === 0 && this.query.page > 1) {
        this.query.page--
        this.getEmployeesListFn()
        return
      }
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 新增员工
    addEmployees() {
      this.showEmpDialog = true
      this.getDepartmentList() // 获取组织架构列表
    },
    // 删除员工
    async delEmployees(id) {
      this.$confirm('此操作不可恢复,确定继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await delEmployeeAPI(id)
          this.$message.success(res.message)
          this.getEmployeesListFn()
        })
        .catch(() => {
          this.$message('已取消')
        })
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesListFn()
    },

    // 格式化聘用形式
    formatFormOfEmployees(num) {
      const obj = {
        1: '正式',
        2: '非正式'
      }
      return obj[num] // 返回数字对应的值
    },
    formatFormFn(row) {
      const obj = Employees.hireType.find(item => Number(item.id) === Number(row.formOfEmployment))
      return obj ? obj.value : '未知'
    },

    // 表格排序
    sortFn(a, b) {
      // a,b是相邻的两个数据对象
      return a.workNumber - b.workNumber
    },

    // 获取组织架构
    async getDepartmentList() {
      const res = await departmentsListAPI()
      // 格式化树形组件的数据
      this.departList = transTree(res.data.depts, '')
    },

    // 新增员工请求
    async addEmp(val) {
      const res = await addEmployeeAPI(val)
      this.getEmployeesListFn()
      this.$message.success(res.message)
    },

    // 关闭弹窗
    closeDialogFn() {
      // 调用子组件重置表单函数
      this.$refs.empForm.resetForm()
    },

    // 上传excel
    uploadExcelFn() {
      this.$router.push('/excel')
    },

    // 下载excel
    downloadExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        const headArr = ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间', '1', '2']
        const keyObj = {
          '序号': 'id',
          '姓名': 'username',
          '头像': 'staffPhoto',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName',
          '入职时间': 'timeOfEntry'
        }
        const valueArr = this.employeesList.map((item, index) => {
          // Object.values(对象) 收集传入的对象的value形成一个新数组
          const newArr = []
          headArr.forEach(zhKey => {
            const enkey = keyObj[zhKey] // 取出中文的key所对应的英文
            // 格式化id
            if (enkey === 'id') {
              newArr.push(index + 1)
            } else if (enkey === 'formOfEmployment') { // 格式化聘用形式
              const data = Employees.hireType.find(obj => Number(obj.id) === Number(item[enkey]))
              newArr.push(data ? data.value : '未知')
            } else {
              const value = item[enkey] // 取出英文的key所对应的值
              newArr.push(value) // 添加到新数组里
            }
          })
          return newArr
        })
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: headArr, // 表头 必填
          data: valueArr, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 分配角色按钮
    addRoleBtnFn(roleId) {
      this.userId = roleId // 设置角色id,接口需要
      this.showRoleDialog = true
      this.getUserRoles()
    },

    // 分配角色弹窗关闭
    closeFn() {
      this.showRoleDialog = false
    },

    // 获取角色列表
    async getRolesListFn() {
      const res = await getRolesAPI({
        page: 1,
        pagesize: 1000 // 解决分配角色弹窗角色显示不全
      })
      this.roleList = res.data.rows
    },

    // 获取员工的现有角色列表
    async getUserRoles() {
      const res = await getUserDetailByIdAPI(this.userId)
      if (!res.success) return this.$message.error(res.message)
      this.roleIds = res.data.roleIds || [] // 没有数据时传入空数组 解决没有角色数据时报错的bug
    },

    // 设置用户的角色
    async addRoleConfirmFn(roleIdArr) {
      const res = await assignRolesAPI({ id: this.userId, roleIds: roleIdArr }) // 传入需要的参数
      if (!res.success) return
      this.getUserRoles()
      this.$message.success(res.message)
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}</style>
